<?php

/**
 * Description of QuoteController
 *
 * @author NE
 */
class Backend_QuoteController extends RCMS_Core_BaseController {

	/**
	 * Data from shopping card config
	 * 
	 * @var array Name value pairs
	 */
	private $_shoppingConfig = array();

	/**
	 * Data from system config
	 *
	 * @var array Name value pairs
	 */
	private $_systemConfig = array();

	/**
	 * Initialization of the controller
	 * 
	 */
	public function init() {
        parent::init();
        parent::checkLogin();
        $this->_model = new Default_Model_QuoteModel();
    }

	/**
	 * Index action.
	 *
	 * Shows quote existing and new quotes list
	 */
	public function indexAction() {
		$this->_helper->getHelper('layout')->disableLayout();

		//assigning variables
		//quote statuses
		$this->view->quotesAvstatuses = array(
			'new'  => 'New',
			'sent' => 'Sent',
			'sold' => 'Sold',
			'lost' => 'Lost'
		);
		//information about all quotes
		$this->view->quotesData = $this->_getAllQuotes();
		$this->view->websiteUrl = $this->getWebsiteUrl();
		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	/**
	 * Edit action.
	 *
	 */
	public function editAction() {
//		$this->_helper->getHelper('layout')->disableLayout();
		
		$quoteId = $this->getRequest()->getParam('qid');
		if($quoteId) {
			$generator = new RCMS_Object_Generator_Generator();
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cartData = $userCart->getCartData();
			//counting total price of all items in the user's cart
			$totalPrice = 0;
			foreach($cartData as $key => $value) {
				$totalPrice += $value['price'] * $value['count'];
			}

			$this->view->needsUpdate = false;
			if(preg_match('/' . RCMS_Object_QuickConfig_QuickConfig::$temporaryNewQuoteName . '[0-9]+-[0-9]+/', $quote->getName())) {
				$this->view->needsUpdate = true;
			}
			//assigning varriables
			//text for email that will be sent to the user. This text will appear in the bootm left textarea of the screen
			$this->view->mailToUser     = $generator->generateQuoteMailToUser($quote->getId(), $userCart->getName());
			//flag shows that quote already has preview
			$this->view->hasPreview     = ($quote->getContent() != '');
			$this->view->quoteId        = $quote->getId();
			$this->view->quoteName      = $quote->getName();
			//internal message for this quote. This text will appear in the bottom right textarea of the screen
			$this->view->quoteIntMsg    = $quote->getInternalMessage();
			$this->view->totalPrice     = $totalPrice;
			//all items in user's cart
			$this->view->cartData       = $cartData;
			$this->view->shoppingConfig = $this->_model->selectShoppingConfig();
			$this->view->cartId         = $userCart->getId();
			$this->view->userMail       = $userCart->getEmail();
			$this->view->quoteEdit      = true;
			$this->view->additionalUserData = array(
				'address1' => $userCart->getAddress1(),
				'address2' => $userCart->getAddress2(),
				'country'  => $userCart->getCountry(),
				'state'    => $userCart->getState(),
				'city'     => $userCart->getCity(),
				'zip'      => $userCart->getZip(),
				'phone'    => $userCart->getPhone()
			);
		}
		$this->view->websiteUrl = $this->getWebsiteUrl();
		
		//for translator
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}


	public function addnewAction() {
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart();
		$timePostfix = date('Ymd-His');
		$userCart->setName(RCMS_Object_QuickConfig_QuickConfig::$temporaryNewQuoteName . $timePostfix);
		$userCart->setEmail('email@email.com');
		$cartId = $userCart->save();
		$quote = new RCMS_Object_Quote_Quote();
		$quote->setShoppingCartId($cartId);
		$quote->setName($userCart->getName());
		$quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_NEW);
		$quoteId = $quote->save();
		$this->_redirect($this->getWebSiteUrl() . 'sys/backend_quote/edit/qid/' . $quoteId);
	}

	public function updatequoteoncreationAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$quoteName = $this->getRequest()->getParam('qName');
			$quoteMail = $this->getRequest()->getParam('qMail');

			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$quote->setName($quoteName);
			$quote->save();

			$cart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$cart->setName($quoteName);
			$cart->setEmail($quoteMail);
			$cart->setCountry($this->getRequest()->getParam('country'));
			$cart->setState($this->getRequest()->getParam('state'));
			$cart->setCity($this->getRequest()->getParam('city'));
			$cart->setZip($this->getRequest()->getParam('zip'));
			$cart->setAddress1($this->getRequest()->getParam('address1'));
			$cart->setAddress2($this->getRequest()->getParam('address2'));
			$cart->setPhone($this->getRequest()->getParam('phone'));
			$cart->save();
			
			echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
	}

	/**
	 * Update quote status. (AJAX calling in quote.js)
	 * 
	 */
	public function updatestatusAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$status = $this->getRequest()->getParam('status');
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$quote->setStatus($status);
			$result = $quote->save();
			if($result) {
				echo json_encode(array('error' => 0, 'msg' => 'success'));
			}
			else {
				echo json_encode(array('error' => 1, 'msg' => 'Can\'t update quote status. Something went wrong'));
			}
		}
	}

	/**
	 * Delete quote. (AJAX calling in quote.js)
	 *
	 */
	public function deletequoteAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		if($this->getRequest()->isPost()) {
			$quoteId = intval($this->getRequest()->getParam('qid'));
			$quote = new RCMS_Object_Quote_Quote($quoteId);
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			if($quote->delete()) {
				$result = $userCart->delete();
				if($result) {
					echo json_encode(array('error' => 0, 'msg' => 'success'));
				}
				else {
					echo json_encode(array('error' => 1, 'msg' => 'Unable to remove user cart. Something went wrong'));
				}
			}
			else {
				echo json_encode(array('error' => 1, 'msg' => 'Unable to remove quote. Something went wrong'));
			}

		}
	}

	/**
	 * Generate quote action (AJAX calling in quote.js)
	 *
	 * Generate quote content for user and sends him an email with link to his quote preview
	 * 
	 */
	public function generateAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$generator = new RCMS_Object_Generator_Generator();
		$this->_shoppingConfig = $this->_model->selectShoppingConfig();
		$this->_systemConfig = $this->_model->selectSystemConfig();
		
		$quoteId = $this->getRequest()->getParam('qid');
		$quote = new RCMS_Object_Quote_Quote($quoteId);

		//text to put in email to user
		$userMailText = $this->getRequest()->getParam('usrMailText');
		//sending email to user
		$mailSent = $this->_sendMailToUser($quote->getShoppingCartId(), $userMailText);

		//if mail sent, then we will generate quote content and set quote status as "sent"
		if($mailSent === true) {
			$userCart = new RCMS_Object_Shopping_ShoppingUserCart($quote->getShoppingCartId());
			$quote->setContent($generator->generateQuoteContent($quote, $userCart));
			$quote->setInternalMessage(RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->getRequest()->getParam('intMessage')));
			$quote->setStatus(RCMS_Object_Quote_Quote::Q_STATUS_SENT);
			$quote->save();

			//send response wich shows that everything went well
			echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
		else {
			//if mail not sent, send error response
			echo json_encode(array('error' => 1, 'msg' => 'Can not send email. Quote was not generated'));
		}
	}

	/**
	 * Show quote preview
	 */
	public function previewAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$preQuoteInfo = explode('.', $this->getRequest()->getParam('qid'));
		if($preQuoteInfo[0] != $preQuoteInfo[2]) {
			echo '<h1>Ooops! Wrong quote?</h1>';
			exit;
		}
		$quoteId = $preQuoteInfo[0];
		$quote = new RCMS_Object_Quote_Quote($quoteId);
		echo $this->_translator->processScreen($quote->getContent());
	}

	public function addproducttocartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		$cartId = intval($this->getRequest()->getParam('cid'));
		$productId = intval($this->getRequest()->getParam('pid'));

		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();
		//var_dump($cartData);
		if(array_key_exists($productId, $cartData)) {
			$cartData[$productId]['count']++;
		}
		else {
			$product = new RCMS_Object_Product_Product($productId);
			$cartData[$productId] = array(
				'count' => 1,
				'photo' => $product->getPhoto(),
				'name'  => $product->getName(),
				'price' => $product->getPrice(),
				'note'  => ''
			);
		}
		$userCart->setCartData($cartData);
		$result = $userCart->save();
		if($result) {
			echo json_encode(array('error' => 0, 'msg' => 'success'));
		}
		else {
			echo json_encode(array('error' => 1, 'msg' => 'Can not add product. Something went wrong'));
		}
	}

	/**
	 * Update user cart
	 * 
	 */
	public function updatecartAction() {
		$this->_helper->getHelper('layout')->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);
		$cartId = $this->getRequest()->getParam('qid');
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($cartId);
		$cartData = $userCart->getCartData();
		//item that should be removed
		$toRemove = json_decode($this->getRequest()->getParam('toRemove'));
		//items wich price should be updated
		$toUpdatePrice = json_decode($this->getRequest()->getParam('toUpdPrice'));
		//items wich note should be updated
		$notes = json_decode($this->getRequest()->getParam('notes'));
		//items wich quantity should be updated
		$toUpdateQty = json_decode($this->getRequest()->getParam('toUpdQty'));
		//remove items from user cart
		if(!empty ($toRemove)) {
			foreach ($toRemove as $remItem) {
				if(array_key_exists($remItem, $cartData)) {
					unset ($cartData[$remItem]);
				}
			}
		}
		//update items price
		if(!empty ($toUpdatePrice)) {
			foreach ($toUpdatePrice as $priceItem) {
				$priceItemExploded = explode(',', $priceItem);
				if(array_key_exists($priceItemExploded[0], $cartData)) {
					$cartData[$priceItemExploded[0]]['price'] = $priceItemExploded[1];
				}
			}
		}
		//udate items qty
		if(!empty($toUpdateQty)) {
			foreach($toUpdateQty as $qtyItem) {
				$qtyItemExploded = explode(',', $qtyItem);
				if(array_key_exists($qtyItemExploded[0], $cartData)) {
					if($qtyItemExploded[1] == 0) {
						unset ($cartData[$qtyItemExploded[0]]);
						continue;
					}
					if($cartData[$qtyItemExploded[0]]['count'] != $qtyItemExploded[1]) {
						$cartData[$qtyItemExploded[0]]['count'] = $qtyItemExploded[1];
					}
				}
			}
		}
		//update items notes
		if(!empty($notes)) {
			foreach($notes as $noteData) {
				$expNote = explode(',', $noteData);
				if(array_key_exists($expNote[0], $cartData)) {
					$cartData[$expNote[0]]['note'] = $expNote[1];
				}
			}
		}
		//saving cart
		$userCart->setCartData($cartData);
		$userCart->save();
	}

	/**
	 * Getting data about quotes from database
	 * 
	 */
	private function _getAllQuotes() {
		$quotesData = $this->_model->selectAllQuotes();
		return $quotesData;
	}

	/**
	 * Sending mail to the user
	 *
	 */
	private function _sendMailToUser($shoppingCartId, $mailText) {
		$userCart = new RCMS_Object_Shopping_ShoppingUserCart($shoppingCartId);
		$mail = new RCMS_Object_Mailer_Mailer();
		if($this->_systemConfig['use_smtp']) {
			$mail->setSmtpConfig($this->_systemConfig['smtp_login'], $this->_systemConfig['smtp_password'], $this->_systemConfig['smtp_host']);
			$mail->setTransport(RCMS_Object_Mailer_Mailer::MAIL_TYPE_SMTP);
		}
		$mail->setFrom($this->_shoppingConfig['company']);
		$mail->setFromMail($this->_shoppingConfig['email']);
		$mail->setTo($userCart->getName());
		$mail->setToMail($userCart->getEmail());
		$mail->setSubject('Quote');
		$mail->setBody($mailText);
		return $mail->send();
	}
}

